<template>
  <el-row :gutter="20">
    <el-col :span="16">
      <el-table :data="tableData" stripe style="width: 100%">
        <el-table-column prop="bookingNumber" label="#" />
        <el-table-column prop="name" label="Name" />
        <el-table-column prop="date" label="Date" />
        <el-table-column prop="from" label="From" />
        <el-table-column prop="to" label="To" />
        <el-table-column prop="bookingStatus" label="Status">
          <template #default="scope">
            {{ scope.row.bookingStatus === "CONFIRMED" ? "✅" : "❌" }}
          </template>
        </el-table-column>
        <el-table-column prop="bookingClass" label="Booking class" />
        <el-table-column label="Operations" fixed="right" width="180">
          <template #default="scope">
            <el-button size="small" type="primary">
              更改预定
            </el-button>
            <el-button size="small" type="danger">
              退订
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-col>

    <el-col :span="8" style="background-color: aliceblue; padding: 20px;">
      <div style="height: 500px; overflow: auto; margin-bottom: 20px;">
        <el-timeline style="max-width: 100%">
          <el-timeline-item
              v-for="(activity, index) in activities"
              :key="index"
              :icon="activity.icon"
              :type="activity.type"
              :color="activity.color"
              :size="activity.size"
              :hollow="activity.hollow"
              :timestamp="activity.timestamp"
          >
            {{ activity.content }}
          </el-timeline-item>
        </el-timeline>
      </div>
      <div id="container">
        <div id="chat">
          <el-input
              v-model="msg"
              input-style="width: calc(100% - 70px); height: 50px; margin-right: 10px;"
              :rows="2"
              type="text"
              placeholder="请输入您的问题..."
              @keydown.enter="sendMsg"
          />
          <el-button @click="sendMsg" style="height: 50px;">发送</el-button>
        </div>
      </div>
    </el-col>
  </el-row>
</template>

<script lang="ts">
import { MoreFilled } from '@element-plus/icons-vue';
import { ref, onMounted } from "vue";
import axios from 'axios';

export default {
  setup() {
    // 聊天记录
    const activities = ref([
      {
        content: '⭐欢迎来到图灵航空✈！请问有什么可以帮您的?',
        timestamp: new Date().toLocaleString(),
        color: '#0bbd87',
      },
    ]);

    // 输入框内容
    const msg = ref('');

    // 预订列表数据
    const tableData = ref([]);

    // SSE连接实例
    let eventSource = null;

    /**
     * 发送消息并建立SSE连接
     */
    const sendMsg = () => {
      // 过滤空消息
      if (!msg.value.trim()) return;

      // 关闭之前的SSE连接（关键：避免多个连接同时推送）
      if (eventSource) {
        eventSource.close();
        eventSource = null;
      }

      // 添加用户消息到聊天记录
      activities.value.push({
        content: `你: ${msg.value}`,
        timestamp: new Date().toLocaleString(),
        size: 'large',
        type: 'primary',
        icon: MoreFilled,
      });

      // 记录等待消息的索引（动态获取当前最后一条消息的索引）
      const waitingIndex = activities.value.length;

      // 添加等待提示
      activities.value.push({
        content: '正在输入...',
        timestamp: new Date().toLocaleString(),
        color: '#0bbd87',
      });

      // 发起SSE请求（对中文参数进行编码）
      const encodedMessage = encodeURIComponent(msg.value);
      eventSource = new EventSource(`http://localhost:8080/ai/generateStreamAsString?message=${encodedMessage}`);

      // 清空输入框
      msg.value = '';

      // 接收服务器推送的消息
      eventSource.onmessage = (event) => {
        // 处理结束标记
        if (event.data === '[complete]') {
          eventSource.close();
          getBookings(); // 刷新预订列表
          return;
        }

        // 动态更新当前等待消息的内容（关键修复：使用waitingIndex定位）
        if (activities.value[waitingIndex]) {
          activities.value[waitingIndex].content += event.data;
        }
      };

      // 连接建立时清空等待提示
      eventSource.onopen = () => {
        if (activities.value[waitingIndex]) {
          activities.value[waitingIndex].content = '';
        }
      };

      // 处理连接错误
      eventSource.onerror = (error) => {
        console.error('SSE连接错误:', error);
        if (activities.value[waitingIndex]) {
          activities.value[waitingIndex].content = '连接失败，请重试';
        }
        eventSource.close();
        eventSource = null;
      };
    };

    /**
     * 获取预订列表数据
     */
    const getBookings = () => {
      axios.get('http://localhost:8080/booking/list')
          .then((response) => {
            tableData.value = response.data;
          })
          .catch((error) => {
            console.error('获取预订列表失败:', error);
          });
    };

    // 组件挂载时加载预订列表
    onMounted(() => {
      getBookings();
    });

    return {
      activities,
      msg,
      tableData,
      sendMsg,
      getBookings,
    };
  },
};
</script>

<style scoped>
#chat {
  display: flex;
  align-items: center;
}

.el-timeline {
  padding-left: 10px;
}

.el-timeline-item__timestamp {
  font-size: 12px;
  color: #666;
}

/* 滚动条美化 */
::-webkit-scrollbar {
  width: 6px;
  height: 6px;
}

::-webkit-scrollbar-thumb {
  background-color: #ccc;
  border-radius: 3px;
}
</style>
